package com.example.tellwin.home;

import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.apkfuns.logutils.LogUtils;
import com.example.tellwin.MainApplication;
import com.example.tellwin.R;
import com.example.tellwin.base.CpBaseFragment;
import com.example.tellwin.base.DaggerRxComponent;
import com.example.tellwin.common.Common;
import com.example.tellwin.event.WebSocketEvent;
import com.example.tellwin.home.act.ActDetailActivity;
import com.example.tellwin.home.act.HuoDongListActivity;
import com.example.tellwin.home.act.QuestionDetailActivity;
import com.example.tellwin.home.act.SearchActivity;
import com.example.tellwin.home.act.TeacherDetailActivity;
import com.example.tellwin.home.adpater.BannerAdapter;
import com.example.tellwin.home.adpater.KnowledgeAdapter;
import com.example.tellwin.home.adpater.PopularActivitiesAdapter;
import com.example.tellwin.home.adpater.TeactherTeamAdpater;
import com.example.tellwin.home.bean.ActivitiesBean;
import com.example.tellwin.home.bean.BannerBean;
import com.example.tellwin.home.bean.ColumnBean;
import com.example.tellwin.home.bean.HomeNumberBean;
import com.example.tellwin.home.bean.KnowdegeBean;
import com.example.tellwin.home.bean.QuestionBean;
import com.example.tellwin.home.bean.TeactherTeamBean;
import com.example.tellwin.home.contract.NormalHomeContract;
import com.example.tellwin.home.presenter.NormalHomePresenter;
import com.example.tellwin.utils.ToastUtil;
import com.example.tellwin.view.ShareDialog;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.youth.banner.Banner;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.listener.OnBannerListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 *
 */
public class StudentHomeFragment extends CpBaseFragment implements OnBannerListener, NormalHomeContract.View {

    @BindView(R.id.scrollvew)
    NestedScrollView scrollView;
    @BindView(R.id.home_search_ll)
    LinearLayout homeSearchLl;
    @BindView(R.id.home_search_tv)
    TextView homeSearchTv;
    @BindView(R.id.home_banner)
    Banner homeBanner;
    @BindView(R.id.onlne_teacher_number_tv)
    TextView onlneTeacherNumberTv;
    @BindView(R.id.onlne_teacher_ll)
    LinearLayout onlneTeacherLl;
    @BindView(R.id.asking_question_number_tv)
    TextView askingQuestionNumberTv;
    @BindView(R.id.asking_question_ll)
    LinearLayout askingQuestionLl;
    @BindView(R.id.knowledge_tab_layout)
    CommonTabLayout knowledgeTabLayout;
    @BindView(R.id.teacther_team_rv)
    RecyclerView teactherTeamRv;
    @BindView(R.id.activities_more_tv)
    TextView activitiesMoreTv;
    @BindView(R.id.popular_activities_rv)
    RecyclerView popularActivitiesRv;
    @BindView(R.id.popular_knowledge_rv)
    RecyclerView popularKnowledgeRv;
    @BindView(R.id.title_tv)
    TextView titleTv;
    @BindView(R.id.content_tv)
    TextView contentTv;
    @BindView(R.id.share_iv)
    ImageView shareIv;
    @BindView(R.id.like_iv)
    ImageView likeIv;
    @BindView(R.id.item_popluar_knowdege_view)
    RelativeLayout itemPopluarKnowdegeView;
    @BindView(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;

    private Unbinder unbinder;


    private TeactherTeamAdpater teactherTeamAdpater;
    private PopularActivitiesAdapter popularActivitiesAdapter;
    private KnowledgeAdapter knowledgeAdapter;
    private List<BannerBean> bannerBeans = new ArrayList<>();
    private List<TeactherTeamBean> teactherTeamBeans = new ArrayList<>();
    private List<ActivitiesBean> activitiesBeans = new ArrayList<>();
    private List<KnowdegeBean> knowdegeBeans = new ArrayList<>();
    private List<ColumnBean> columnBeans = new ArrayList<>();

    @Inject
    NormalHomePresenter mPresenter;

    private int curPage = 0;
    private int pageSize = 20;
    private int total = 1;//总条数

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public View onCreateRootView(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        unbinder = ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        initView(view);
        initData();
        initEvent();
        return view;
    }

    private void initView(View view) {

        DaggerRxComponent.builder()
                .baseAppComponent(MainApplication.getAppComponent())
                .build()
                .inject(this);
        mPresenter.attachView(this);

        teactherTeamAdpater = new TeactherTeamAdpater();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        teactherTeamRv.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                int position = parent.getChildAdapterPosition(view); // item position
                if (position == 0) {
                    outRect.left = getResources().getDimensionPixelOffset(R.dimen.dp_15);
                } else if (position == teactherTeamBeans.size() - 1) {
                    outRect.left = getResources().getDimensionPixelOffset(R.dimen.dp_10);
                    outRect.right = getResources().getDimensionPixelOffset(R.dimen.dp_15);
                } else {
                    outRect.left = getResources().getDimensionPixelOffset(R.dimen.dp_10);
                }
            }
        });
        teactherTeamRv.setLayoutManager(linearLayoutManager);
        teactherTeamRv.setAdapter(teactherTeamAdpater);

        LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(getContext());
        linearLayoutManager1.setOrientation(RecyclerView.HORIZONTAL);
        popularActivitiesRv.setLayoutManager(linearLayoutManager1);
        popularActivitiesRv.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                int position = parent.getChildAdapterPosition(view); // item position
                outRect.left = getResources().getDimensionPixelOffset(R.dimen.dp_15);
                if (position == activitiesBeans.size() - 1) {
                    outRect.right = getResources().getDimensionPixelOffset(R.dimen.dp_15);
                }
            }
        });
        popularActivitiesAdapter = new PopularActivitiesAdapter();
        popularActivitiesRv.setAdapter(popularActivitiesAdapter);

        LinearLayoutManager linearLayoutManager2 = new LinearLayoutManager(getContext());
        linearLayoutManager2.setOrientation(RecyclerView.VERTICAL);
        popularKnowledgeRv.setLayoutManager(linearLayoutManager2);
        popularKnowledgeRv.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                int position = parent.getChildAdapterPosition(view); // item position
                if (position != 0) {
                    outRect.top = getResources().getDimensionPixelOffset(R.dimen.dp_15);
                }
            }
        });
        knowledgeAdapter = new KnowledgeAdapter();
        popularKnowledgeRv.setAdapter(knowledgeAdapter);
    }

    private void initData() {
        mPresenter.homeBanner();
        mPresenter.homeColumn();
        mPresenter.getTeacherTeam();
        mPresenter.getActiviteList();
    }


    private void initEvent() {
        teactherTeamAdpater.setOnTeacherItemClickListener((position, teactherTeamBean) -> {
            Intent intent = new Intent(getActivity(), TeacherDetailActivity.class);
            intent.putExtra(Common.TEACHER_ID, teactherTeamBean.getUserId());
            intent.putExtra(Common.TEACHER_NAME, teactherTeamBean.getRealName());
            startActivity(intent);
        });
        homeSearchLl.setOnClickListener(v -> {
            startActivity(SearchActivity.class);
        });
        popularActivitiesAdapter.setItemPopularActivitiesClickListener((position, activitiesBean) -> {
            Bundle bundle = new Bundle();
            bundle.putSerializable(Common.ACTIVITY, activitiesBean);
            StudentHomeFragment.this.startActivity(bundle, ActDetailActivity.class);
        });
        knowledgeTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                ColumnBean columnBean = columnBeans.get(position);
                if (columnBean.getContentBean() != null && columnBean.getContentBean().getQuestionList() != null && columnBean.getContentBean().getQuestionList().size() > 0) {
                    setQuestionData(columnBean.getContentBean().getQuestionList());
                } else {
                    mPresenter.indexQuestionList(position, columnBeans.get(position));
                }
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        scrollView.setOnScrollChangeListener((NestedScrollView.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> {
            // 滚动到底
            if (columnBeans == null || columnBeans.size() <= 0) {
                return;
            }
            if (scrollY == (v.getChildAt(0).getMeasuredHeight() - v.getMeasuredHeight())) {
                LogUtils.e("滚动到底部");
                mPresenter.indexQuestionList(knowledgeTabLayout.getCurrentTab(), columnBeans.get(knowledgeTabLayout.getCurrentTab()));
            }
        });
        knowledgeAdapter.setKnowledgeListener(new KnowledgeAdapter.KnowledgeListener() {
            @Override
            public void onItemLikeClick(int position, QuestionBean questionBean) {
                mPresenter.likeQuestion(questionBean.getQuestionId(), position + 1);
            }

            @Override
            public void onItemShareClick(int position, QuestionBean questionBean) {
                ShareDialog shareDialog = new ShareDialog(getContext() , 2 , questionBean.getQuestionId() , questionBean.getQuestionName());
                shareDialog.show();
            }

            @Override
            public void onItemClick(int position, QuestionBean questionBean) {
                Intent intent = new Intent(getActivity(), QuestionDetailActivity.class);
                intent.putExtra(Common.QUESTION, questionBean.getQuestionId());
                startActivity(intent);
            }
        });
        likeIv.setOnClickListener(v -> {
            if (titleTv.getTag() != null) {
                QuestionBean questionBean = (QuestionBean) titleTv.getTag();
                mPresenter.likeQuestion(questionBean.getQuestionId(), 0);
            }
        });
        shareIv.setOnClickListener(v -> {
            QuestionBean questionBean = (QuestionBean) titleTv.getTag();
            ShareDialog shareDialog = new ShareDialog(getContext() , 2 , questionBean.getQuestionId() ,questionBean.getQuestionName());
            shareDialog.show();
        });
        itemPopluarKnowdegeView.setOnClickListener(v -> {
            if (titleTv.getTag() != null) {
                QuestionBean questionBean = (QuestionBean) titleTv.getTag();
                Intent intent = new Intent(getActivity(), QuestionDetailActivity.class);
                intent.putExtra(Common.QUESTION, questionBean.getQuestionId());
                startActivity(intent);
            }
        });
        refreshLayout.setOnRefreshListener(() -> {
            initData();
        });
    }

    @Subscribe
    public void onEvent(HomeNumberBean event) {
        onlneTeacherNumberTv.setText(event.userCount + "人");
        askingQuestionNumberTv.setText(event.questionsNum + "单");
    }



    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void OnBannerClick(Object data, int position) {
        BannerBean bannerBean = (BannerBean) data;
        try {
            String url = bannerBean.getBannerUrl();
            if(!url.contains("http")){
                url = "http://" + url;
            }
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }catch (Exception e){
            e.printStackTrace();
            ToastUtil.show(getContext() , "网址有误:" + bannerBean.getBannerUrl());
        }
    }


    @Override
    public void homeBannerResult(List<BannerBean> bannerBeans) {
        this.bannerBeans = bannerBeans;
        homeBanner.setAdapter(new BannerAdapter(bannerBeans));
        homeBanner.setIndicator(new CircleIndicator(getContext()));
        homeBanner.setIndicatorNormalColor(getResources().getColor(R.color.home_banner_normal_indictor));
        homeBanner.setIndicatorSelectedColor(getResources().getColor(R.color.home_banner_selected_indictor));
        homeBanner.setOnBannerListener(this);
        refreshLayout.setRefreshing(false);
    }

    @Override
    public void homeColumnResult(List<ColumnBean> columnBeans) {
        this.columnBeans = columnBeans;
        ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>(columnBeans);
        knowledgeTabLayout.setTabData(mTabEntities);
        if (columnBeans != null && columnBeans.size() > 0) {
            mPresenter.indexQuestionList(0, columnBeans.get(0));
        }
        refreshLayout.setRefreshing(false);
    }

    @Override
    public void indexQuestionListResult(int position, ColumnBean columnBean) {
        columnBeans.set(position, columnBean);
        if (position != knowledgeTabLayout.getCurrentTab()) {
            return;
        }
        if (columnBean.getContentBean() != null && columnBean.getContentBean().getQuestionList() != null && columnBean.getContentBean().getQuestionList().size() > 0) {
            itemPopluarKnowdegeView.setVisibility(View.VISIBLE);
            List<QuestionBean> questionBeans = columnBean.getContentBean().getQuestionList();
            setQuestionData(questionBeans);
        } else {
            titleTv.setText("");
            contentTv.setText("");
            titleTv.setTag(null);
            itemPopluarKnowdegeView.setVisibility(View.GONE);
            knowledgeAdapter.setKnowdegeBeans(new ArrayList<>());
        }

        refreshLayout.setRefreshing(false);
    }

    @Override
    public void teacherTeamResult(List<TeactherTeamBean> teactherTeamBeans) {
        teactherTeamAdpater.setBeans(teactherTeamBeans);
        refreshLayout.setRefreshing(false);
    }

    @Override
    public void activiteListResult(List<ActivitiesBean> activitiesBeans) {
        popularActivitiesAdapter.setBeans(activitiesBeans);
        refreshLayout.setRefreshing(false);
    }

    @Override
    public void likeQuestionResult(int position) {
        List<QuestionBean> questionBeans = columnBeans.get(knowledgeTabLayout.getCurrentTab()).getContentBean().getQuestionList();
        int like = questionBeans.get(position).getIsLike();
        if (like == 0) {
            like = 1;
        } else {
            like = 0;
        }
        questionBeans.get(position).setIsLike(like);
        setQuestionData(questionBeans);
    }

    @Override
    public void onFail() {
        refreshLayout.setRefreshing(false);
    }

    private void setQuestionData(List<QuestionBean> questionBeans) {
        List<QuestionBean> questionBeanList = new ArrayList<>(questionBeans);
        LogUtils.e(questionBeanList);
        QuestionBean questionBean = questionBeanList.remove(0);
        itemPopluarKnowdegeView.setVisibility(View.VISIBLE);
        titleTv.setText(questionBean.getQuestionName());
        contentTv.setText(questionBean.getIndexContent());
        likeIv.setSelected(questionBean.getIsLike() == 1);
        titleTv.setTag(questionBean);
        knowledgeAdapter.setKnowdegeBeans(questionBeanList);
    }

    @OnClick({R.id.share_iv, R.id.like_iv, R.id.activities_more_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.share_iv:
                break;
            case R.id.like_iv:
                break;
            case R.id.activities_more_tv:
                startActivity(HuoDongListActivity.class);
                break;
        }
    }
}
